<?php

namespace Admin\Controller;

use Core\Constant;
use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Session\AdminSessionHelper;
use Exception;
use Logger;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;


class DishController extends AdminBaseController {



    public function indexAction()
    {

        $categoryTable = $this->getTableFinder()->getCategoryTable(
            AdminSessionHelper::getCurrentLang());
        $category = $categoryTable->getRootCategory(Constant::$CATEGORY_GROUP_DISH);
        $categoryTree = $category->getComboTree();

        $subCategory = $categoryTable->getRootCategory(Constant::$CATEGORY_GROUP_SUBDISH);
        $subCategoryTree = $subCategory->getComboTree();
        return new ViewModel(array('allCategory'=>$categoryTree, 'allSubCategory'=>$subCategoryTree));

    }

    public function listAction()
    {

        try{
            $name = $this->params()->fromPost('name');
            $category = $this->params()->fromPost('category');

            $dishTable = $this->getTableFinder()->getDishTable(
                AdminSessionHelper::getCurrentLang());


            $searchOption = array();
            $searchOption['name'] = $name;
            $searchOption['category'] = $category;


            $sortData = $this->params()->fromPost("sort");
            if($sortData){
                $order = array();
                foreach ($sortData as $sortField) {
                    $field = $sortField['field'];
                    $direction = $sortField['dir'];
                    $orderClause = $field." ".$direction;
                    array_push($order, $orderClause);
                }
            }else{
                $order = array("id desc");
            }

            $page = $this->params()->fromPost("page");
            $rows = $this->params()->fromPost("pageSize");
            $offset = ($page - 1) * $rows;
            $allDishes = $dishTable->search(true, $offset, $rows, $order,$searchOption);
            return new JsonModel(array('success'=>true,
                'rows'=>$allDishes["rows"]->toArray(),
                'total'=>$allDishes["total"]));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function addAction()
    {
        $viewModel = new ViewModel();
        $id =  $this->params()->fromQuery("id");
        if($id){
            $dishTable = $this->getTableFinder()->getDishTable(
                AdminSessionHelper::getCurrentLang());
            $dish = $dishTable->getDish($id);
            $viewModel->setVariable('dishItem',$dish);

        }

        $categoryTable = $this->getTableFinder()->getCategoryTable(
            AdminSessionHelper::getCurrentLang());

        $category = $categoryTable->getRootCategory(Constant::$CATEGORY_GROUP_DISH);
        $rs = $category->getAllChildren();
        $allMainCat = array();
        foreach ($rs as $aCat) {
            array_push($allMainCat, $aCat->toArray());
        }

        $subCategory = $categoryTable->getRootCategory(Constant::$CATEGORY_GROUP_SUBDISH);
        $rs = $subCategory->getAllChildren();
        $allSubCat = array();
        foreach ($rs as $aCat) {
            array_push($allSubCat, $aCat->toArray());
        }

        $viewModel->setVariable('allCategory',$allMainCat);
        $viewModel->setVariable('allSubCategory',$allSubCat);

        $unitTable = $this->getTableFinder()->getUnitTable(
            AdminSessionHelper::getCurrentLang());

        $allUnitAsArray = $unitTable->getAllAsArray();
        $viewModel->setVariable('allUnitAsArray', $allUnitAsArray);

        $dishTagTable = $this->getTableFinder()->getDishTagTable(
            AdminSessionHelper::getCurrentLang());
        $allTags = $dishTagTable->getDistinctTags();
        $viewModel->setVariable('allTags', $allTags);

        return $viewModel;

    }

    function saveDishAction(){
        try{

            $id = $this->params()->fromPost('id');

            $dishTable = $this->getTableFinder()->getDishTable(
                AdminSessionHelper::getCurrentLang());

            $transactionProxy = $this->getTableGatewayTransactionProxy();
            $transactionProxy->setAbstractTable($dishTable);
            if(!$id){
                $transactionProxy->addDish($this->params()->fromPost());
//                $dishTable->addDish($this->params()->fromPost());
            }else{
                $dishTable->updateDish($this->params()->fromPost(), $id);
            }

            return new JsonModel(array("success"=>true));
        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function getDishForViewAction(){
        try{

            $id = $this->params()->fromPost('id');

            $lang = AdminSessionHelper::getCurrentLang();
            $dishTable = $this->getTableFinder()->getDishTable(
                $lang);
            $dishItem = $dishTable->getDish($id);
            if(!$dishItem) throw new BusinessException('Chưa truyền id');

            $allTags = $dishItem->getDishTags($lang);
            $tagsAsString = '';
            if($allTags)
            foreach ($allTags as $aTag) {
                $tagsAsString = $tagsAsString.','.$aTag->tag;
            }
            if(strlen($tagsAsString) > 0)
                $tagsAsString = substr($tagsAsString, 1);

            $allMainCategories = $dishItem->getDishCategoryByGroup($lang, Constant::$CATEGORY_GROUP_DISH);
            $allSubCategories = $dishItem->getDishCategoryByGroup($lang, Constant::$CATEGORY_GROUP_SUBDISH);

            $mainCategoryAsString = '';
            if($allMainCategories)
            foreach ($allMainCategories as $aCategory) {
                if($aCategory->isLeaf())
                $mainCategoryAsString = $mainCategoryAsString.','.$aCategory->name;
            }
            if(strlen($mainCategoryAsString) > 0)
                $mainCategoryAsString = substr($mainCategoryAsString, 1);

            $subCategoryAsString = '';
            if($allSubCategories)
                foreach ($allSubCategories as $aCategory) {
                    if($aCategory->isLeaf())
                        $subCategoryAsString = $subCategoryAsString.','.$aCategory->name;
                }
            if(strlen($subCategoryAsString) > 0)
                $subCategoryAsString = substr($subCategoryAsString, 1);

            return new JsonModel(array("success"=>true,
                'name'=>$dishItem->getName($lang),
                'description'=>$dishItem->getDescription($lang),
                'tag'=>$tagsAsString, 'primary_category'=>$mainCategoryAsString,
                'sub_category'=>$subCategoryAsString,));
        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeAction(){

        try{

            $id = $this->params()->fromPost('id');
            $dishTable = $this->getTableFinder()->getDishTable(
                AdminSessionHelper::getCurrentLang()
            );
            $item = $dishTable->getDish($id);
            if(!$item){
                throw new BusinessException("Không tìm thấy món ăn phù hợp");
            }

            $dishTable->delete($id);
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

}